/*
 * Copyright (C) 2021 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.dona.imsidetector.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager2.widget.ViewPager2;

import com.dona.imsidetector.R;
import com.dona.imsidetector.adpter.BlackWhiltListItemAdapter;
import com.dona.imsidetector.adpter.ImsiBlackWhiltListAdapter;
import com.dona.imsidetector.bean.vo.BwListRespVo;
import com.dona.imsidetector.bean.vo.BwListVo;
import com.dona.imsidetector.bean.vo.ListItemVo;
import com.dona.imsidetector.core.BaseFragment;
import com.dona.imsidetector.databinding.FragmentBlackwhiteBinding;
import com.dona.imsidetector.db.dao.ItemDao;
import com.dona.imsidetector.db.dao.ListDao;
import com.dona.imsidetector.db.entity.BwList;
import com.dona.imsidetector.db.entity.ListItem;
import com.dona.imsidetector.socket.UDPSocket;
import com.dona.imsidetector.utils.DeviceUtil;
import com.dona.imsidetector.utils.IMSIUtil;
import com.dona.imsidetector.utils.XToastUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.textfield.TextInputLayout;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.tencent.mmkv.MMKV;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.callback.impl.IProgressResponseCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xui.XUI;
import com.xuexiang.xui.adapter.simple.AdapterItem;
import com.xuexiang.xui.adapter.simple.XUISimpleAdapter;
import com.xuexiang.xui.utils.StatusBarUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.edittext.ClearEditText;
import com.xuexiang.xui.widget.popupwindow.popup.XUISimplePopup;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 这个只是一个空壳Fragment，只是用于演示而已
 *
 * @author xuexiang
 * @since 2019-07-08 00:52
 */
@Page(name = "黑白名单")
public class BlackWhiteFragment extends BaseFragment<FragmentBlackwhiteBinding> {

    private static final String TAG = "BlackWhiteFragment";

    @NonNull
    @Override
    protected FragmentBlackwhiteBinding viewBindingInflate(LayoutInflater inflater, ViewGroup container) {
        return FragmentBlackwhiteBinding.inflate(inflater, container, false);
    }

//    /**
//     * @return 返回为 null意为不需要导航栏
//     */
//    @Override
//    protected TitleBar initTitle() {
//        TitleBar titleBar = super.initTitle()
//                .setImmersive(true);
//        titleBar.setBackgroundColor(Color.TRANSPARENT);
//        titleBar.setTitle("");
//        titleBar.setLeftImageDrawable();
//        return null;
//    }


    /**
     * 初始化控件
     */
    @Override
    protected void initViews() {

//        StatusBarUtils.fullScreen(this.getActivity());
//        XUI.initTheme(getActivity());
//        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        btnCloseInfo = (Button) findViewById(R.id.btn_close_info);
//        noImsiListll = (LinearLayout) findViewById(R.id.noImsiList);
        listOperation = (BottomNavigationView) findViewById(R.id.list_bottom_navigation);
        listOperation.setItemIconTintList(null);
        listOperation.setItemTextColor(ColorStateList.valueOf(getResources().getColor(R.color.list_item)));

        // 名单列表
        blackWhiteListRecyclerView = (RecyclerView) findViewById(R.id.list_recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this.getContext());
//        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        blackWhiteListRecyclerView.setLayoutManager(linearLayoutManager);

//        blackWhiteListRecyclerView.getRecycledViewPool().setMaxRecycledViews(0,1);
//        blackWhiteListRecyclerView.setItemViewCacheSize(0);
//        updateImsiLists();
//        if(bwLists.size() == 0){
//            blackWhiteListRecyclerView.setVisibility(VIS);
//        }
        imsiBlackWhiltListAdapter = new ImsiBlackWhiltListAdapter(this, bwLists);
        blackWhiteListRecyclerView.setAdapter(imsiBlackWhiltListAdapter);
        imsiBlackWhiltListAdapter.notifyDataSetChanged();

        // imsi列表
        listItemOperation = (BottomNavigationView) findViewById(R.id.list_item_bottom_navigation);
        listItemOperation.setItemIconTintList(null);
        listItemOperation.setItemTextColor(ColorStateList.valueOf(getResources().getColor(R.color.list_item)));

        listItemRecycleView = (RecyclerView) findViewById(R.id.list_item_recyclerView);
        LinearLayoutManager itemLinearLayoutManager = new LinearLayoutManager(this.getContext());
//        itemLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        listItemRecycleView.setLayoutManager(itemLinearLayoutManager);
        listItemRecycleView.getRecycledViewPool().setMaxRecycledViews(0, 1);
        blackWhiltListItemAdapter = new BlackWhiltListItemAdapter(this, listItems);
        listItemRecycleView.setAdapter(blackWhiltListItemAdapter);
        blackWhiltListItemAdapter.notifyDataSetChanged();

//        initMenuPopup();
//        btnMenuPopup = (Button) findViewById(R.id.btnMenuPopup);
        initSwipeRefresh();
        initListener();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
//        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }


    private RelativeLayout operLayout;
    private RelativeLayout infoLayout;
    private Button btnCloseInfo;

    private RecyclerView blackWhiteListRecyclerView;
    private List<BwList> bwLists = new ArrayList<>();
    private ImsiBlackWhiltListAdapter imsiBlackWhiltListAdapter;
    private BottomNavigationView listOperation;
    public List<BwList> operationsList = new ArrayList<>();


    private List<ListItem> listItems = new ArrayList<>();
    private RecyclerView listItemRecycleView;
    private BlackWhiltListItemAdapter blackWhiltListItemAdapter;
    private BottomNavigationView listItemOperation;
    public List<ListItem> operationsListItemList = new ArrayList<>();
//
//    private XUISimplePopup mMenuPopup;
//    public static AdapterItem[] menuItems = new AdapterItem[]{
//            new AdapterItem("无人机", R.drawable.vector_aircraft),
//    };
//
//    private void initMenuPopup() {
//        XUISimplePopup.OnPopupItemClickListener popupItemClickListener = new XUISimplePopup.OnPopupItemClickListener() {
//            @Override
//            public void onItemClick(XUISimpleAdapter adapter, AdapterItem item, int position) {
//                switch (position) {
//                    case 0:
//                        if (operationsList.size() == 1) {
//                            BwList bwList = operationsList.get(0);
//                            Intent intent = new Intent(this.getContext(), IMSISearchActivity.class);
//                            intent.putExtra("listid", bwList.getUuid());
//                            startActivity(intent);
//                        } else {
//                            new MaterialDialog.Builder(this.getContext())
//                                    .title("提示")
//                                    .content("请先选择黑白名单")
//                                    .positiveText("确定")
//                                    .show();
//                        }
//
//                        break;
//                }
//
//            }
//        };
//        mMenuPopup = new XUISimplePopup(this.getContext(), menuItems)
//                .create(popupItemClickListener);
//        mMenuPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
////                StatusBarUtils.fullScreen(this.getContext());
//            }
//        });
//    }



    // 智能刷新开始

    private SwipeRefreshLayout refreshLayout;


    private void initSwipeRefresh() {
//        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresh_layout);
//        recyclerView = (SwipeRecyclerView)findViewById(R.id.recycler_view);

//        WidgetUtils.initRecyclerView(recyclerView);
//
//        //必须在setAdapter之前调用
//        recyclerView.setSwipeMenuCreator(swipeMenuCreator);
//        //必须在setAdapter之前调用
//        recyclerView.setOnItemMenuClickListener(mMenuItemClickListener);
//        recyclerView.setAdapter(mAdapter = new SwipeImsiBlackWhiltListAdapter(getDemoData(),R.layout.adapter_black_white_imsi_list_item, listItemClickListener));
//
//        refreshLayout.setColorSchemeColors(0xff0099cc, 0xffff4444, 0xff669900, 0xffaa66cc, 0xffff8800);

        initRefreshListener();
    }

    private void refresh() {
        Log.e(TAG, "列表自动刷新");
        binding.refreshLayout.setRefreshing(true);
        loadData();
    }

    private void loadData() {
        Log.e(TAG, "加载数据");

        new Handler().postDelayed(() -> {
            getBWList();
        }, 1000);
    }

    private Collection<BwListVo> getDemoData() {
        Collection<BwListVo> bwLists = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            BwListVo bwListVo = new BwListVo();
            bwListVo.setTitle("test" + i);
            bwListVo.setUser("13800138000");
            bwListVo.setUuid(DeviceUtil.getUUID());
            bwListVo.setCreateTime(new Date());
            bwLists.add(bwListVo);
        }
        return bwLists;
    }

    private void initRefreshListener() {
        //下拉刷新
        binding.refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.e(TAG, "refreshLayout onRefresh: ");
                loadData();
            }
        });
        refresh(); //第一次进入触发自动刷新，演示效果
    }

    //智能刷新结束


//    private void initMenuPopup() {
//        AdapterItem[] menuItems = new AdapterItem[]{
//                new AdapterItem("无人机", R.drawable.vector_aircraft),
//        };
//        mMenuPopup = new XUISimplePopup(this.getContext(), menuItems)
//                .create(new XUISimplePopup.OnPopupItemClickListener(){
//
//                    @Override
//                    public void onItemClick(XUISimpleAdapter adapter, AdapterItem item, int position) {
//                        switch (position){
//                            case 0:
//                                Log.e(TAG, "mMenuPopup onItemClick: ");
//                                break;
//                        }
//                    }
//                });
//
//    }


    public void updateImsiItems(String listid) {
        List<ListItem> allByListId = ItemDao.findAllByListId(listid);
        if (null != allByListId) {
            Log.e(TAG, "updateImsiItems: size=" + listItems);
            listItems = allByListId;
            blackWhiltListItemAdapter.setListItems(listItems);
            blackWhiltListItemAdapter.notifyDataSetChanged();
        }
    }

    public void updateImsiLists() {
        List<BwList> all = ListDao.findAll();
        if (null != all) {
            bwLists = all;
            Log.e("updateImsiLists", "updateImsiLists: " + bwLists);
            if (null != imsiBlackWhiltListAdapter) {
                imsiBlackWhiltListAdapter.notifyDataSetChanged();
            }
        } else {
            Log.e("updateImsiLists", "updateImsiLists: " + "null");
        }
    }

    private void initListener() {
//
//        btnMenuPopup.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (operationsList.size() == 1) {
//                    BwList bwList = operationsList.get(0);
//                    Intent intent = new Intent(this.getContext(), IMSISearchActivity.class);
//                    intent.putExtra("listid", bwList.getUuid());
//                    startActivity(intent);
//                } else {
//                    new MaterialDialog.Builder(this.getContext())
//                            .title("提示")
//                            .content("请先选择黑白名单")
//                            .positiveText("确定")
//                            .show();
//                }
//            }
//        });

        listOperation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                String title = item.getTitle().toString();
                Log.e(TAG, "onNavigationItemSelected: " + title);
                switch (title) {
                    case "新建":
//                        String user = MMKV.defaultMMKV().getString("user", "13800138000");
//                        BwList bwList = new BwList(user, DeviceUtils.getRandomString(20));
//                        String res = ListDao.add(bwList);
//                        if(null != res){
//                            XToastUtils.error("插入失败：" + res);
//                        }else {
//                            BwList list = ListDao.find(bwList.getUuid());
//                            if(null != list){
//                                bwLists.add(0, list);
//                                imsiBlackWhiltListAdapter.notifyDataSetChanged();
//                            }
//                        }
                        new MaterialDialog.Builder(getContext())
                                .title("名单标题")
                                .input("名单的标题", "", false, ((dialog, input) -> {
                                })).onPositive((dialog, which) -> {
                            String t = dialog.getInputEditText().getText().toString();
                            String user = "test";
                            BwList bwList = new BwList(user, t);

                            // 更新到服务器中
                            addBwListToService(bwList);

                            // 插入数据库
                            String res = ListDao.add(bwList);
                            if (null != res) {
                                XToastUtils.error("插入失败：" + res);
                            } else {
                                BwList list = ListDao.find(bwList.getUuid());
                                if (null != list) {
                                    bwLists.add(0, list);
                                    imsiBlackWhiltListAdapter.notifyDataSetChanged();
                                }
                            }
                        }).negativeText("取消").show();
                        break;
                    case "删除":
                        // 去掉删除功能
                        if (operationsList.size() == 1) {

                            Log.e(TAG, "onNavigationItemSelected: 删除 ");
                            BwList listitem = operationsList.get(0);
                            int index = DeviceUtil.getItemIndex(bwLists, listitem);
                            if (index > -1) {
                                try {
                                    deleteBwListFromService(listitem);
                                    String msg = ListDao.delete(listitem);
                                    bwLists.remove(index);
                                    imsiBlackWhiltListAdapter.notifyDataSetChanged();
                                    ItemDao.deteteAllByListId(listitem.getUuid());
                                    XToastUtils.success("删除名单：" + listitem.getTitle() + "成功");
                                    listItems.clear();
                                    blackWhiltListItemAdapter.setListItems(listItems);
                                    blackWhiltListItemAdapter.notifyDataSetChanged();
                                    operationsList.clear();

                                } catch (Exception e) {
                                    Log.e(TAG, "delete item failed: " + e.toString());
                                    XToastUtils.success("删除名单：" + listitem.getTitle() + "失败");
                                }
                            }
                        }
                        break;
                    case "全选":
                        break;
                }
                return false;
            }
        });

        listItemOperation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                String title = item.getTitle().toString();
                switch (title) {
                    case "新建":
                        if (operationsList.size() == 1) {
                            BwList bwList = operationsList.get(0);
                            addListItemNewDialog(bwList);
                        }else {
                            XToastUtils.info("请先选择名单");
                        }
                        Log.e(TAG, "listItemOperation.onNavigationItemSelected: 新建");
                        break;
                    case "删除":
                        // 去掉删除功能
                        if (operationsListItemList.size() == 1) {
                            Log.e(TAG, "onNavigationItemSelected: 删除 ");
                            ListItem listItem = operationsListItemList.get(0);
                            int index = listItems.indexOf(listItem);
                            if (index > -1) {
                                try {
                                    deleteLisItemFromService(listItem);
                                    ItemDao.delete(listItem);
                                    listItems.remove(index);
                                    blackWhiltListItemAdapter.notifyDataSetChanged();
                                    XToastUtils.success("删除" + listItem.getImsiAddr() + "成功");

                                    operationsListItemList.clear();

                                } catch (Exception e) {
                                    Log.e(TAG, "delete item failed: " + e.toString());
                                    XToastUtils.success("删除" + listItem.getImsiAddr() + "失败");
                                }
                            }
                        }



                        break;
                    case "全选":
                        break;
                }
                return false;
            }
        });


        btnCloseInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.infoLayout.setVisibility(View.GONE);
                binding.operLayout.setVisibility(View.VISIBLE);
                listOperation.setVisibility(View.GONE);
            }
        });
    }


    private MaterialDialog addListItemDialog;

    public void addListItemNewDialog(BwList bwList) {

        addListItemDialog = new MaterialDialog.Builder(this.getContext())
                .autoDismiss(false)
                .customView(R.layout.dialog_add_listitem, true)
                .title("添加黑白名单项")
                .positiveText("确定")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        View rvv = dialog.getView();
                        TextInputLayout tlImsiAddr = (TextInputLayout) rvv.findViewById(R.id.tl_imsiaddr);
                        CheckBox cbIsWhite = (CheckBox) rvv.findViewById(R.id.cb_iswhite);

                        String imsi = tlImsiAddr.getEditText().getText().toString();
                        boolean isWhite = cbIsWhite.isChecked();

                        String errMsg = checkImsiFormat(imsi);
                        if(null != errMsg){

                            tlImsiAddr.setErrorEnabled(true);
                            tlImsiAddr.setHintEnabled(false);
                            tlImsiAddr.setError(errMsg);
                        }else {
                            ListItem listItem = new ListItem();
                            listItem.setUuid(DeviceUtil.getUUID());
                            listItem.setListId(bwList.getUuid());
                            listItem.setImsiAddr(imsi);
                            listItem.setIsWhite(isWhite == true ? 1 : 0);
                            listItem.setIsp(IMSIUtil.checkImsiType(imsi));
                            listItem.setCreateTime(new Date());
                            // 临时用city字段来存储参数
                            listItem.setCity(IMSIUtil.getMobileAll(imsi));
                            addLisItemToService(listItem);
                            dialog.dismiss();
                        }

                    }
                })
                .negativeText("取消")
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                })
                .build();



        WindowManager.LayoutParams p = addListItemDialog.getWindow().getAttributes();
        p.width = 1200;
        p.height = 700;
        addListItemDialog.getWindow().setAttributes(p);
        View rvv = addListItemDialog.getView();
        if (operationsListItemList.size() == 1) {
            Log.e(TAG, "onNavigationItemSelected: 删除 ");
            ListItem listItem = operationsListItemList.get(0);
            TextInputLayout tlImsiAddr = (TextInputLayout) rvv.findViewById(R.id.tl_imsiaddr);
            tlImsiAddr.getEditText().setText(listItem.getImsiAddr());
            CheckBox cbIsWhite = (CheckBox) rvv.findViewById(R.id.cb_iswhite);
            cbIsWhite.setChecked(listItem.getIsWhite() == 1 ? true: false);
        }
        // imsi跟踪号码


        addListItemDialog.show();


    }

    private String checkImsiFormat(String imsi) {
        boolean matches = Pattern.matches("^460\\d{12}", imsi);
        if(matches){
            return null;
        }else {
            return "imsi是以460开头的15位数字";
        }
    }

    private Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .create();

    private ListItem genRandonImsiItem(String listid) {
        Random random = new Random();
        ListItem listItem = new ListItem(listid, random.nextInt(2), IMSIUtil.genFakerImsi());
        listItem.setProvince("广东");
        listItem.setCity("东莞");
        return listItem;
    }

    public void setListBottomNavigation() {
        Log.e(TAG, "setListBottomNavigation: ");
        binding.infoLayout.setVisibility(View.VISIBLE);
        listOperation.setVisibility(View.VISIBLE);
    }







    private void addBwListToService(BwList bwList) {
        OkHttpClient client = new OkHttpClient();
        String url =   DetectorFragment.hostAddress + "api.php/mobile/bwlist/add";
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();

        //json
        MediaType jsonType = MediaType.parse("application/json; charset=utf-8");

        RequestBody jsonbody = RequestBody.create(jsonType, gson.toJson(new BwListVo(bwList)));

        Request request = new Request.Builder()
                .post(jsonbody)
                .url(urlBuilder.build())
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "addBwListToService: onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e(TAG, "addBwListToService: onResponse: " + response.body().string());
            }
        });
    }


    private void deleteBwListFromService(BwList bwList) {
//        OkHttpClient client = new OkHttpClient();
//        String url = "http://192.168.3.4:889/api.php/mobile/bwlist/delete";
//        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
//
//        //json
        MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
//
        RequestBody jsonbody = RequestBody.create(jsonType, gson.toJson(new BwListVo(bwList)));
//
//        Request request = new Request.Builder()
//                .post(jsonbody)
//                .url(urlBuilder.build())
//                .build();
//
//        Call call = client.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.e(TAG, "addBwListToService: onFailure: " + e.getMessage());
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                Log.e(TAG, "addBwListToService: onResponse: " + response.body().string());
//            }
//        });

        XHttp.post("api.php/mobile/bwlist/delete")
                .keepJson(true)
                .timeOut(1000 * 300)
                .connectTimeout(1000 * 300)
                .readTimeOut(1000 * 300)
                .requestBody(jsonbody)
                .onMainThread(true)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String response) throws Throwable {
                        Log.e(TAG, "addBwListToService: onResponse: " + response);

                    }
                    @Override
                    public void onError(ApiException e) {
                        Log.e(TAG, "addBwListToService: onFailure: " + e.getMessage());

                    }
                });



    }


    private void addLisItemToService(ListItem listItem) {

        Log.e(TAG, "addLisItemToService: " + listItem.toString());
//        OkHttpClient client = new OkHttpClient();
//        String url = "http://192.168.3.4:889/api.php/mobile/listitem/add";
//        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();

        //json
        MediaType jsonType = MediaType.parse("application/json; charset=utf-8");

        RequestBody jsonbody = RequestBody.create(jsonType, gson.toJson(new ListItemVo(listItem)));

//        Request request = new Request.Builder()
//                .post(jsonbody)
//                .url(urlBuilder.build())
//                .build();
//
//        Call call = client.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.e(TAG, "addLisItemToService: onFailure: " + e.getMessage());
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String resp = response.body().string();
//                Log.e(TAG, "addLisItemToService: onResponse: " + resp);
//                try {
//                    JsonElement jsonElement = new Gson().toJsonTree(resp);
//                    JsonObject asJsonObject = jsonElement.getAsJsonObject();
//                    String data = asJsonObject.get("data").getAsJsonObject().toString();
//                    ListItemVo listItemVo = gson.fromJson(data, ListItemVo.class);
//                    ListItem item = new ListItem(listItemVo);
//                    ItemDao.add(item);
//                    listItems.add(0, item);
//                    blackWhiltListItemAdapter.notifyItemInserted(0);
////                    blackWhiltListItemAdapter.notifyDataSetChanged();
//                }catch (Exception e){
//                    Log.e(TAG, "addLisItemToService gson: " + e.getLocalizedMessage());
//                    e.printStackTrace();
//                }
//
//
//            }
//        });
        listItem.setCity(null);
        ItemDao.add(listItem);
        listItems.add(0, listItem);
        blackWhiltListItemAdapter.notifyItemInserted(0);

        XHttp.post("api.php/mobile/listitem/add")
                .keepJson(true)
                .timeOut(1000 * 30)
                .connectTimeout(1000 * 30)
                .readTimeOut(1000 * 30)
                .requestBody(jsonbody)
                .onMainThread(true)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String response) throws Throwable {
                        Log.e(TAG, "addBwListToService: onResponse: " + response);

                        String data = gson.fromJson(response,JsonObject.class).get("data").getAsJsonObject().toString();
                        ListItemVo listItemVo = gson.fromJson(data, ListItemVo.class);
                        ListItem item = new ListItem(listItemVo);
                        item.setUuid(listItem.getUuid());
                        ItemDao.update(item);
//                        listItems.add(0, item);
//                        blackWhiltListItemAdapter.notifyItemInserted(0);
                    }
                    @Override
                    public void onError(ApiException e) {
                        Log.e(TAG, "addBwListToService: onFailure: " + e.getMessage());

                    }
                });

    }


    private void deleteLisItemFromService(ListItem listItem) {
//        OkHttpClient client = new OkHttpClient();
//        String url =  "http://192.168.3.4:889/api.php/mobile/listitem/delete";
//        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();

        //json
        MediaType jsonType = MediaType.parse("application/json; charset=utf-8");

        RequestBody jsonbody = RequestBody.create(jsonType, gson.toJson(new ListItemVo(listItem)));

//        Request request = new Request.Builder()
//                .post(jsonbody)
//                .url(urlBuilder.build())
//                .build();

//        Call call = client.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.e(TAG, "deleteLisItemFromService: onFailure: " + e.getMessage());
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                Log.e(TAG, "deleteLisItemFromService: onResponse: " + response.body().string());
//            }
//        });

        XHttp.post("api.php/mobile/listitem/delete")
                .keepJson(true)
                .timeOut(1000 * 300)
                .connectTimeout(1000 * 300)
                .readTimeOut(1000 * 300)
                .requestBody(jsonbody)
                .onMainThread(true)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String response) throws Throwable {
                        Log.e(TAG, "deleteLisItemFromService: onSuccess: " + response);

                    }
                    @Override
                    public void onError(ApiException e) {
                        Log.e(TAG, "deleteLisItemFromService: onFailure: " + e.getMessage());

                    }
                });

    }


    public void addOperationImsiItemList(ListItem listItem) {
        for (ListItem item : operationsListItemList) {
            if (item.getUuid() == listItem.getUuid()) {
                return;
            }
        }
        operationsListItemList.add(listItem);
    }

    public void deleteOperationImsiItemList(ListItem listItem) {
        for (int i = 0; i < operationsListItemList.size(); i++) {
            if (listItem.getUuid() == operationsListItemList.get(i).getUuid()) {
                operationsListItemList.remove(i);
            }
        }
    }


    public void addOperationsList(BwList bwList) {
        for (BwList item : operationsList) {
            if (item.getUuid() == bwList.getUuid()) {
                return;
            }
        }
        operationsList.add(bwList);
    }

    public void deleteOperationsList(BwList bwList) {
        for (int i = 0; i < operationsList.size(); i++) {
            if (bwList.getUuid() == operationsList.get(i).getUuid()) {
                operationsList.remove(i);
            }
        }
    }


    private OkHttpClient okHttpClient = new OkHttpClient();

    public void getBWList() {
        XHttp.post("api.php/mobile/bwlist/byuser.html")
                .keepJson(true)
                .timeOut(1000 * 300)
                .connectTimeout(1000 * 300)
                .readTimeOut(1000 * 300)
                .params("user", "test")
                .onMainThread(true)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String response) throws Throwable {
                        //上传图片
//                        XToastUtils.success("更新成功");
//                                            mMinLoadingDialog.dismiss();
//                        final String res = response.body().string();
                        Log.e(TAG, "okhttp onResponse: " + response);
                        String data = gson.fromJson(response, JsonObject.class).get("data").toString();
                         Log.e(TAG, "okhttp onResponse data: " + data);


                         if(null != data && !"null".equals(data)){
                             BwListRespVo bwListRespVo = gson.fromJson(data, BwListRespVo.class);
                             if (bwListRespVo.getCode().equals(0) && bwListRespVo.getData().size() > 0) {
                                 Log.e(TAG, "onResponse: " + bwListRespVo);
                                 loadBw(bwListRespVo.getData());
                             }else {
                                 if (refreshLayout != null) {
                                     refreshLayout.setRefreshing(false);
                                 }
                             }
                         }else {
                             XToastUtils.error("没有数据！");
                             blackWhiltListItemAdapter.notifyDataSetChanged();
                             if (binding.refreshLayout != null) {
                                 binding.refreshLayout.setRefreshing(false);
                             }
                         }



                    }

                    @Override
                    public void onError(ApiException e) {
//                        XToastUtils.error("更新失败" + e.getDetailMessage());

                        Log.e(TAG, "onError: " + e.getDetailMessage());
                        XToastUtils.error("无法连接服务器");

                        List<BwList> all = ListDao.findAll();
                        bwLists.addAll(all);
                        imsiBlackWhiltListAdapter.notifyDataSetChanged();
                        blackWhiltListItemAdapter.notifyDataSetChanged();
                        if (binding.refreshLayout != null) {
                            binding.refreshLayout.setRefreshing(false);
                        }
                    }
                });


//        XHttp.get("api.php/mobile/bwlist/byuser.html").baseUrl("http://nasas.oicp.vip:889/")

    }


    private void clearListAndItem() {
        ListDao.clear();
        ItemDao.clear();
    }

    private void loadBw(List<BwListRespVo.ListAndItem> data) {
        if (bwLists.size() > 0) {
            bwLists.clear();
            blackWhiltListItemAdapter.notifyDataSetChanged();
        }
        clearListAndItem();

        for (BwListRespVo.ListAndItem listAndItem : data) {
            BwList bwl = new BwList(listAndItem.getBwlist());
            String error = ListDao.add(bwl);
            if (null != error) {
                Log.e(TAG, "ListDao.add: " + error);
            }
            bwLists.add(bwl);
            for (ListItemVo listItemVo : listAndItem.getListitem()) {
                ListItem listItem = new ListItem(listItemVo);
                ItemDao.add(listItem);
            }

        }
        blackWhiltListItemAdapter.notifyDataSetChanged();
        if (binding.refreshLayout != null) {
            binding.refreshLayout.setRefreshing(false);
        }
    }



}
